package com.shd.edanpei.ui.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shd.edanpei.BuildConfig;
import com.shd.edanpei.R;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.bean.ActivityBean;
import com.shd.edanpei.bean.BannerBean;
import com.shd.edanpei.db.DaoManager;
import com.shd.edanpei.presenter.contract.ListviewItemOnClick;
import com.shd.edanpei.ui.activity.FullDialogActivity;
import com.shd.edanpei.ui.adapter.HomeBannerAdapter;
import com.shd.edanpei.ui.adapter.HomeBannerAdapter1;
import com.shd.edanpei.ui.adapter.HomeBannerVRAdapter;
import com.shd.edanpei.ui.adapter.MenuAdapter;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.MenuModel;
import com.shd.edanpei.bean.NoticeModel;
import com.shd.edanpei.bean.PagingModel;
import com.shd.edanpei.enums.UrlEnum;
import com.shd.edanpei.ui.adapter.holder.BannerHolder;
import com.shd.edanpei.ui.activity.DynamicsActivity;
import com.shd.edanpei.ui.activity.MeProductsActivity;
import com.shd.edanpei.ui.activity.WebActivity;
import com.shd.edanpei.util.BannerIndicator;
import com.shd.edanpei.util.PagerSnapHelperUtil;
import com.shd.edanpei.util.SmoothLinearLayoutManager;
import com.shd.edanpei.view.notice.NoticeView;
import com.vegen.open.library.VRecyclerViewBanner;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/10/17.
 * 首页 头部布局
 */

public class HomeHeadView extends LinearLayout implements ListviewItemOnClick{

    private Context mContext;

    private ConvenientBanner banner;
    private BannerHolder bannerHolder;
    private final int[] banner_point = {R.drawable.shape_banner_point1, R.drawable.shape_banner_point2};

    private RecyclerView menuRecyclerView;
    private MenuAdapter mAdapter;

    private NoticeView noticeView;

    private ImageView ivActivity;
    private View view_hight;
    private VRecyclerViewBanner vRecyclerViewBanner;
    private Timer timer;
    private TimerTask timerTask;
    private HomeBannerVRAdapter  homeBannerVRAdapter;


    public HomeHeadView(Context context) {
        super(context);
        init(context);
    }

    public HomeHeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public HomeHeadView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        inflate(mContext, R.layout.home_head, this);
        initView();
        requestBannerData();
        initMenu();
        initNoticeData();
        requestNoticeData();
        requestEvent();
        initListener();
    }

    private void initNoticeData() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if(BuildConfig.IS_RELEASE_URL)
                requestNoticeData();
            }
        };
        timer.schedule(timerTask, 0, 10 * 1000);
    }


    private void initView() {
        ivActivity = findViewById(R.id.iv_activity);
        view_hight=findViewById(R.id.view_hight);
        vRecyclerViewBanner=findViewById(R.id.vr_view_banner);
    }

    /**
     * 获取banner数据
     */
    public void requestBannerData() {
        ApiCreator.getApi().getBanner()
                .compose(RxTransformer.<List<BannerBean>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<BannerBean>>() {
                    @Override
                    protected void onSuccess(List<BannerBean> data) {
                        List<String> list = new ArrayList<>();
                        for (int i = 0; i < data.size(); i++) {
                            list.add(data.get(i).getPicUrl());
                        }
                        initBanner(data);
                    }
                });
    }
    private  LinearLayoutManager layoutManager1;
    private RecyclerView recyclerView;
    private HomeBannerAdapter1 adapter;
    private ArrayList<String> list;
    private BannerIndicator bannerIndicator;
    /**
     * Banner
     */
    List<BannerBean> data=new ArrayList<>();
    private void initBanner(final List<BannerBean> data) {
        this.data = data;
        list = new ArrayList<>();
        for (BannerBean datum : data) {
            list.add(datum.getPicUrl());
        }
        //测试代码
        homeBannerVRAdapter = new HomeBannerVRAdapter(mContext, list, this);
        vRecyclerViewBanner.setAdapter(homeBannerVRAdapter);
        vRecyclerViewBanner.setOnPageChangeListener(new VRecyclerViewBanner.OnPageChangeListener() {
            @Override
            public void onPageSelected(int i) {
                bannerIndicator.setPosition(i);
            }
        });
        bannerIndicator = findViewById(R.id.indicator);
        bannerIndicator.setNumber(list.size());
    }
    private void requestNoticeData() {
        if(null==DaoManager.getInstance().getUserBean())
            return;
        ApiCreator.getApi().getNotice()
                .compose(RxTransformer.<PagingModel<NoticeModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<PagingModel<NoticeModel>>() {
                    @Override
                    protected void onSuccess(PagingModel<NoticeModel> data) {
                        List<String> list = new ArrayList<>();
                        for (int i = 0; i < data.getList().size(); i++) {
                            list.add(data.getList().get(i).getMessage());
                        }
                        initNotice(list);
                    }
                });
    }


    private void requestEvent() {
        ApiCreator.getApi().activityList(DaoManager.getInstance().getUserBean().getRoleType())
                .compose(RxTransformer.<List<ActivityBean>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<ActivityBean>>() {
                    @Override
                    protected void onSuccess(final List<ActivityBean> data) {
                        if (data != null && data.size() > 0) {
                            ivActivity.setVisibility(VISIBLE);
                            view_hight.setVisibility(GONE);
                            Glide.with(getContext()).load(data.get(0).getTitlePic()).into(ivActivity);
                            final String url = data.get(0).getLink() + "?userId=" + DaoManager.getInstance().getUserBean().getId() + "&accessToken=" + DaoManager.getInstance().getUserBean().getAccessToken();
                            ivActivity.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    WebActivity.start(mContext, data.get(0).getName(), url, UrlEnum.a.getType());
                                }
                            });
                            Bundle bundle = new Bundle();
                            bundle.putString("image", data.get(0).getWindowPic());
                            bundle.putString("name", data.get(0).getName());
                            bundle.putString("url", url);
                            startActivity(FullDialogActivity.class, bundle);
                        } else {
                            ivActivity.setVisibility(GONE);
                            view_hight.setVisibility(VISIBLE);
                        }
                    }
                });
    }

    /**
     * 初始化通知栏
     */
    private void initNotice(List<String> list) {
        noticeView = findViewById(R.id.notice_view);
        noticeView.setNoticeList(list);

    }


    /**
     * 初始化菜单栏
     */
    private void initMenu() {

        List<MenuModel.MenuData> homeMenuList = MenuModel.getHomeMenuList();
        menuRecyclerView = findViewById(R.id.menu_recycler_view);
        GridLayoutManager manager = new GridLayoutManager(mContext, homeMenuList.size());
        menuRecyclerView.setLayoutManager(manager);

        mAdapter = new MenuAdapter(mContext, R.layout.item_home_menu);
        menuRecyclerView.setAdapter(mAdapter);

        mAdapter.setNewData(homeMenuList);
    }


    private void initListener() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MenuModel.MenuData item = mAdapter.getItem(position);
                switch (item.getId()) {
                    case 1:
                        startActivity(MeProductsActivity.class);
                        break;
                    case 2:
                        //中介入口
                        RxBus.get().send(RxBusCode.To_PublishFragment);
                        break;
                    case 3:
                        startActivity(DynamicsActivity.class);
                        break;
                    case 4:
                        WebActivity.start(mContext, item.getMenuName(), null, UrlEnum.j.getType());
                        break;
                    case 5:
                        WebActivity.start(mContext, item.getMenuName(), null, UrlEnum.a.getType());
                        break;
                    default:
                        break;
                }
            }
        });
    }


    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }

    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(mContext, clz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        mContext.startActivity(intent);
    }
    //listview点击事件
    @Override
    public void onItemClick(View view, int position) {
        if (data.get(position).getPosition().equals(BannerBean.APP)) {

        } else if (data.get(position).getPosition().equals(BannerBean.H5)) {
            WebActivity.start(mContext, data.get(position).getName(), data.get(position).getLinkUrl(), 0);
        }
    }

    @Override
    public void onItemLongClick(View view, int position) {

    }




}
